﻿using System;
using System.Collections.Generic;
using ForgetTraffic.DAL.Conctracts;
using ForgetTraffic.DataModel;
using ForgetTraffic.DataTypes;
using StructureMap;

namespace ForgetTraffic.DAL.EntitiesManagers
{
    public class StatusManager
    {

        private static Dictionary<String, tblSysState> _objectStates = new Dictionary<string, tblSysState>();

        private static IRepository<tblSysState> _repository
        {
            get { return ObjectFactory.GetInstance<IRepository<tblSysState>>(); }
        }

    

        /// <summary>
        /// 
        /// </summary>
        /// <param name="code"></param>
        /// <param name="codeParent"></param>
        /// <returns></returns>
        public static tblSysState GetByCodeAndParent( String code, String codeParent)
        {
           
            //Vou verficar se a table que gere a cache ainda nao foi descartada     
            if(_objectStates == null )
                _objectStates = new Dictionary<string, tblSysState>();

            //Vuou verificar se já existem em cache
            CheckAndCreateOnCache(code, codeParent);


            return _objectStates[code];

        }

        public static tblSysState GetByCodeAndParentWhioutCahce(String code, String codeParent)
        {

            tblSysState _state =  _repository.Single(x => x.Code.Equals(code, StringComparison.CurrentCultureIgnoreCase)
                                           &&
                                           x.CodeParent.Equals(codeParent, StringComparison.InvariantCultureIgnoreCase));



            return _state;

        }

        private static void CheckAndCreateOnCache( String code , String codeParent)
        {
            if (!_objectStates.ContainsKey(code))
            {
                tblSysState _state =
                    _repository.Single(x => x.Code.Equals(code, StringComparison.CurrentCultureIgnoreCase)
                                            &&
                                            x.CodeParent.Equals(codeParent, StringComparison.InvariantCultureIgnoreCase));
    
    

                _objectStates.Add(code, _state);
            }

        }


        public static string Update(String code, String codeType, String OldCode)
        {

            tblSysState state =  _repository.Single(x => x.Code.Equals(OldCode));
            

            if (state == null)
            {
                return "Não existem codigo com essa descrição";
            }

            state.Code = code;
            state.Description = DateTime.Now.ToString();

            return "Foi actualizado";

        }


    }
}